package com.ebraga.trackerclub.android.dao.core.webservice;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;

import com.ebraga.trackerclub.android.dao.api.webservice.EntityWSDao;
import com.ebraga.trackerclub.android.exception.BackofficeConnectionException;
import com.ebraga.trackerclub.android.exception.BackofficeUtilException;
import com.ebraga.trackerclub.android.exception.dao.BackofficeConnectionWebServicesException;
import com.ebraga.trackerclub.android.exception.dao.BackofficeIllegalArgumentDaoException;
import com.ebraga.trackerclub.android.exception.dao.BackofficeInvalidURLWebServicesException;
import com.ebraga.trackerclub.android.exception.dao.BackofficeWebServicesException;
import com.ebraga.trackerclub.android.util.webservice.HTTPSClientWrapper;

/**
 * Abstract implementation of {@link EntityWSDao}
 *
 * @param <E> the entity to be send to the web server.
 */
public class AbstractEntityWSDAOImpl<E> implements EntityWSDao<E> {

	private HTTPSClientWrapper<E> httpsClientWrapper;
	private String url;

	public void setHTTPSClientWrapper(HTTPSClientWrapper<E> httpsClientWrapper) {
		this.httpsClientWrapper = httpsClientWrapper;
	}
	
	public void setURL(String url) {
		this.url = url;
	}
	
	@Override
	public boolean insert(Collection<E> entityList) throws BackofficeWebServicesException,
			BackofficeInvalidURLWebServicesException, BackofficeConnectionWebServicesException, BackofficeIllegalArgumentDaoException {
		
		if(httpsClientWrapper == null) {
			throw new BackofficeIllegalArgumentDaoException("httpsClientWrapper parameter cannot be null.");
		}
		
		if(url == null) {
			throw new BackofficeIllegalArgumentDaoException("url parameter cannot be null.");
		}
		
		if(entityList == null || entityList.isEmpty()) {
			throw new BackofficeIllegalArgumentDaoException("entityList cannot be null or empty.");
		}
		
		boolean success = false;
		try {
			new URL(url);
			
			String response = httpsClientWrapper.doPost(url, entityList);
			if(response != null) {
				success = true;
			}
		} catch (BackofficeUtilException e) {
			throw new BackofficeWebServicesException(e);
		} catch (MalformedURLException e) {
			throw new BackofficeInvalidURLWebServicesException("Malformed URL: "+url, e);
		} catch (BackofficeConnectionException e) {
			throw new BackofficeConnectionWebServicesException(e);
		}
		
		return success;
	}

}
